// controller/user_controller.go
package controller

import (
	"backenddev/no1/mvc_study/model"
	"backenddev/no1/mvc_study/view"
	"encoding/json"
	"net/http"
	"strconv"
	"strings"
)

type UserController struct {
	UserRepo model.UserRepository
	View     view.View
}

// 辅助函数：从 URL 提取 ID
func getIDFromRequest(r *http.Request) (int, bool) {
	// 假设路径为 /user/123
	path := r.URL.Path
	parts := strings.Split(path, "/")
	if len(parts) < 3 {
		return 0, false
	}
	id, err := strconv.Atoi(parts[2])
	if err != nil {
		return 0, false
	}
	return id, true
}

func (uc *UserController) GetUser(w http.ResponseWriter, r *http.Request) {
	// 只处理 GET /user/{id}
	if r.Method != "GET" {
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		return
	}

	id, ok := getIDFromRequest(r)
	if !ok {
		http.Error(w, "Invalid user ID", http.StatusBadRequest)
		return
	}

	user, err := uc.UserRepo.FindByID(id)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	// 判断是返回 JSON 还是渲染 HTML
	if r.Header.Get("Accept") == "application/json" {
		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode(user)
		return
	}

	// 默认渲染 HTML 模板
	uc.View.Show(w, "user", user)
}
